import React, { useState, useEffect } from "react";
import {
  Card,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Button,
  message,
  Upload,
  DatePicker,
} from "antd";
import { useParams, history } from "ice";
import { PlusOutlined } from "@ant-design/icons";
import request from "@/utils/request";
import type { UploadFile } from "antd/es/upload/interface";
import moment from "moment";
import { Line } from "@ant-design/charts";

const ProductDetail: React.FC = () => {
  const [form] = Form.useForm();
  const { id } = useParams();
  const [categories, setCategories] = useState([]);
  const [brands, setBrands] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 获取分类列表
  const fetchCategories = async () => {
    const { data, success } = await request({
      url: "/categories",
      method: "get",
    });

    if (success) {
      setCategories(data);
    }
  };

  // 获取品牌列表
  const fetchBrands = async (categoryId?: string) => {
    const { data, success } = await request({
      url: "/brands",
      method: "get",
      params: { categoryId },
    });

    if (success) {
      setBrands(data);
    }
  };

  // 获取商品详情
  const fetchProductDetail = async () => {
    if (!id) return;

    const { data, success } = await request({
      url: `/products/${id}/detail`,
      method: "get",
    });

    if (success) {
      form.setFieldsValue(data);
      setSelectedCategory(data.categoryId);
      setFileList(
        data.images?.map((url, index) => ({
          uid: `-${index}`,
          name: `image-${index}`,
          status: "done",
          url,
        })) || []
      );
      fetchBrands(data.categoryId);
    }
  };

  // 保存商品
  const handleSave = async (values) => {
    const { success } = await request({
      url: id ? `/products/${id}` : "/products",
      method: "post",
      data: {
        ...values,
        images: fileList.map((file) => file.url || file.response?.url),
        _method: id ? "put" : "post",
      },
    });

    if (success) {
      message.success("保存成功");
      history.push("/products/list");
    }
  };

  useEffect(() => {
    fetchCategories();
    if (id) {
      fetchProductDetail();
    }
  }, [id]);

  return (
    <Card title={id ? "编辑商品" : "新增商品"}>
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSave}
        style={{ maxWidth: 600 }}
      >
        <Form.Item name="name" label="商品名称" rules={[{ required: true }]}>
          <Input />
        </Form.Item>

        <Form.Item
          name="mainImage"
          label="商品主图"
          rules={[{ required: true }]}
        >
          <Upload
            listType="picture-card"
            maxCount={1}
            onChange={({ fileList }) => {
              const file = fileList[0];
              form.setFieldValue("mainImage", file?.response?.data?.url || file?.url);
            }}
            customRequest={async ({ file, onSuccess, onError }) => {
              try {
                const formData = new FormData();
                formData.append("file", file);

                const response = await request.post(`/upload?folder=products/main`, formData, {
                  headers: {
                    "Content-Type": "multipart/form-data",
                    Authorization: localStorage.getItem("token"),
                  },
                });

                if (response.success) {
                  onSuccess(response);
                } else {
                  message.error(response.message || "文件上传失败");
                  onError(new Error(response.message || "文件上传失败"));
                }
              } catch (error) {
                console.error("上传失败:", error);
                message.error("文件上传失败，请稍后重试");
                onError(error);
              }
            }}
          >
            {!form.getFieldValue("mainImage") && (
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传</div>
              </div>
            )}
          </Upload>
        </Form.Item>

        <Form.Item label="商品图片列表">
          <Upload
            listType="picture-card"
            fileList={fileList}
            onChange={({ fileList }) => setFileList(fileList)}
            customRequest={async ({ file, onSuccess, onError }) => {
              try {
                const formData = new FormData();
                formData.append("file", file);
                formData.append("folder", "products/gallery");

                const response = await request.post("/upload", formData, {
                  headers: {
                    "Content-Type": "multipart/form-data",
                    Authorization: localStorage.getItem("token"),
                  },
                });

                if (response.success) {
                  onSuccess(response);
                } else {
                  message.error(response.message || "文件上传失败");
                  onError(new Error(response.message || "文件上传失败"));
                  setFileList((prevList) => prevList.filter((item) => item.uid !== file.uid));
                }
              } catch (error) {
                console.error("上传失败:", error);
                message.error("文件上传失败，请稍后重试");
                onError(error);
                setFileList((prevList) => prevList.filter((item) => item.uid !== file.uid));
              }
            }}
            multiple
          >
            {fileList.length >= 8 ? null : (
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传</div>
              </div>
            )}
          </Upload>
        </Form.Item>

        <Form.Item
          name="purchasePrice"
          label="采购价格"
          rules={[{ required: true }]}
        >
          <InputNumber min={0} precision={2} style={{ width: "100%" }} />
        </Form.Item>

        <Form.Item
          name="marketPrice"
          label="当日参考行情价格"
          rules={[{ required: true }]}
        >
          <InputNumber min={0} precision={2} style={{ width: "100%" }} />
        </Form.Item>

        <Form.Item name="marketPriceDate" label="参考行情价格日期">
          <DatePicker style={{ width: "100%" }} />
        </Form.Item>

        {id && (
          <Form.Item label="价格走势">
            <Line
              data={
                form.getFieldValue("priceHistory")?.map((item) => ({
                  date: moment(item.date).format("YYYY-MM-DD"),
                  price: item.price,
                })) || []
              }
              xField="date"
              yField="price"
            />
          </Form.Item>
        )}

        <Form.Item
          name="batchNo"
          label="商品批次号"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>

        <Form.Item name="notice" label="商品注意事项">
          <Input.TextArea rows={4} />
        </Form.Item>

        <Form.Item
          name="categoryId"
          label="商品分类"
          rules={[{ required: true }]}
        >
          <Select
            onChange={(value) => {
              setSelectedCategory(value);
              fetchBrands(value);
              form.setFieldValue("brandId", undefined);
            }}
          >
            {categories.map((cat) => (
              <Select.Option key={cat._id} value={cat._id}>
                {cat.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item name="brandId" label="商品品牌" rules={[{ required: true }]}>
          <Select disabled={!selectedCategory}>
            {brands.map((brand) => (
              <Select.Option key={brand._id} value={brand._id}>
                {brand.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item name="sort" label="排序">
          <InputNumber min={0} style={{ width: "100%" }} />
        </Form.Item>

        <Form.Item name="status" label="状态" valuePropName="checked">
          <Switch />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button
            style={{ marginLeft: 8 }}
            onClick={() => history.push("/products/product")}
          >
            返回
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default ProductDetail;
